package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Customer;
import com.sl.au.entity.CustomerMailingInfo;
import com.sl.au.entity.CustomerPayInfo;
import com.sl.au.entity.CustomerSendInfo;
import com.sl.au.entity.CustomerVisiting;
import com.sl.au.entity.KeyContact;
import com.sl.au.entity.Module;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.User;
import com.sl.au.repository.KeyContactRepository;
import com.sl.au.service.CustomerMailingInfoService;
import com.sl.au.service.CustomerSendInfoService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.CustomerVisitingService;
import com.sl.au.service.EXDECustomerPayInfoService;
import com.sl.au.service.ExdeCustomerAllocationService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;

@RestController
@RequestMapping(value = "/ui/customer")
public class CustomerController extends BaseController {
	private static final Iterable CustomerPayInfo = null;

	@Autowired
	ExdeCustomerAllocationService exdeCustomerAllocationService;
	@Autowired
	EXDECustomerPayInfoService exdeCustomerPayInfoService;
	@Autowired
	CustomerMailingInfoService customerMailingInfoService;
	@Autowired
	CustomerSendInfoService customerSendInfoService;
	
	@Autowired
	CustomerService customerService;
	
	@Autowired
	OperateLogService operateLogService;

	@Autowired
	KeyContactRepository keyContactRepository;

	@Autowired
	CustomerVisitingService customerVisitingService;

	@Autowired
	SaleAreaService saleAreaService;

	@Autowired
	OptionService optionService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("customer/customerIndex");
		String name="customerinfo"; 
        Module module = this.getPageModule(name);
        modelAndView.addObject("module", module);
		return modelAndView;
	}

	// 获得客户信息的列表
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if(key==null){
			key="";
		}
		String name="customerinfo"; 
        Module module = this.getPageModule(name);
        String dataFilter=module.getDataFilter();
        if(dataFilter==null){
        	dataFilter="所有";
        }
        Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior(); 
		String areaName=a.getUser().getSaleArea().getAreaName();
		List<Customer> customers = customerService.getCustomer(start, length, key,dataFilter, superior, areaName,a.getUser().getId());
		long count =0;
		if(dataFilter.equals("所有")){
			count = customerService.getRepository().getCount(key);
		}else if(dataFilter.equals("本部门")){
			count=customerService.getRepository().getCount(key, superior);
		}else if(dataFilter.equals("本片区")){
			count=customerService.getRepository().getCount(key, superior, areaName);
		}else if(dataFilter.equals("本人")){
			count=customerService.getRepository().getCountByUserId(key, a.getUser().getId());
		}
		map.put("data", customers);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/// 验证客户编号是否重复
	@RequestMapping(value = "codeValidate", method = RequestMethod.GET)
	public Map<String, Object> codeValidate(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId=request.getParameter("id");
		String customerCode = request.getParameter("customerCode");
		long count = customerService.codeValidate(customerId, customerCode);
		map.put("code", count);
		return map;
	}

	//// 关键联系人信息列表
	@RequestMapping(value = "getKeyContact", method = RequestMethod.GET)
	public Map<String, Object> getKeyContact(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId = request.getParameter("customerId");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<KeyContact> keyContacts = new ArrayList<KeyContact>();
		if (StringUtils.hasText(customerId)) {
			keyContacts = customerService.getKeyContacts(start, length, key, customerId);
		}
		long count = 0;
		if (key != null) {
			count = customerService.getKeyContactRepository().getKeyCount(customerId, key);
		} else {
			count = customerService.getKeyContactRepository().getKeyCount(customerId);
		}
		map.put("data", keyContacts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/// 增加客户
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView customerAdd(HttpServletRequest request) {
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior(); 
		ModelAndView mv = this.createLayoutView("customer/newcustomer");
		String businessGroup = "行业";
		String regionGroup = "地区";
		String buyerGroup = "买方属性";
		String asset = "资产性质";
		String continuelife = "续存年限";
		String credit = "支付信用";
		String period = "合作期限";
		String customerCode=customerService.getCustomerCode();
		mv.addObject("customerCode", customerCode);
		mv.addObject("saleAreas", saleAreaService.getRepository().findBySuperior(superior));
		mv.addObject("businesses", optionService.getRepository().findByGroup(businessGroup));
		mv.addObject("regions", optionService.getRepository().findByGroup(regionGroup));
		mv.addObject("buyers", optionService.getRepository().findByGroup(buyerGroup));
		mv.addObject("assets", optionService.getRepository().findByGroup(asset));
		mv.addObject("continuelifes", optionService.getRepository().findByGroup(continuelife));
		mv.addObject("credits", optionService.getRepository().findByGroup(credit));
		mv.addObject("periods", optionService.getRepository().findByGroup(period));
		mv.addObject("customers", customerService.getRepository().findAll());
		return mv;
	}

	///// 编辑客户
	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public ModelAndView customerEdit(HttpServletRequest request) {
		/*Account a = this.getMyAccount();
		String name = a.getUser().getName();
		long count = exdeCustomerAllocationService.getAllUserCount(name);*/
		ModelAndView mv = this.createLayoutView("customer/customerEdit");
		String customerId = request.getParameter("customerId");
		String businessGroup = "行业";
		String regionGroup = "地区";
		String buyerGroup = "买方属性";
		String asset = "资产性质";
		String continuelife = "续存年限";
		String credit = "支付信用";
		String period = "合作期限";
		if (customerId != null) {
			Customer customer = customerService.getRepository().findById(customerId);
			//customer.setBuyer(customer.getBuyer()!=null?customer.getBuyer():"");
			mv.addObject("customer", customer);
		}
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior(); 
		List<SaleArea> saleAreas = saleAreaService.getRepository().findBySuperior(superior);
		if (saleAreas.size() > 0) {
			mv.addObject("saleAreas", saleAreas);
		}
		mv.addObject("businesses", optionService.getRepository().findByGroup(businessGroup));
		mv.addObject("regions", optionService.getRepository().findByGroup(regionGroup));
		mv.addObject("buyers", optionService.getRepository().findByGroup(buyerGroup));
		mv.addObject("assets", optionService.getRepository().findByGroup(asset));
		mv.addObject("continuelifes", optionService.getRepository().findByGroup(continuelife));
		mv.addObject("credits", optionService.getRepository().findByGroup(credit));
		mv.addObject("periods", optionService.getRepository().findByGroup(period));
		mv.addObject("customers", customerService.getRepository().findAll());
		return mv;
	}
	
///// 查看客户
	@RequestMapping(value = "see", method = RequestMethod.GET)
	public ModelAndView customerSee(HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("customer/customerRead");
		String customerId = request.getParameter("customerId");
		String businessGroup = "行业";
		String regionGroup = "地区";
		String buyerGroup = "买方属性";
		String asset = "资产性质";
		String continuelife = "续存年限";
		String credit = "支付信用";
		String period = "合作期限";
		if (customerId != null) {
			Customer customer = customerService.getRepository().findById(customerId);
			mv.addObject("customer", customer);
		}
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior(); 
		List<SaleArea> saleAreas = saleAreaService.getRepository().findBySuperior(superior);
		if (saleAreas.size() > 0) {
			mv.addObject("saleAreas", saleAreas);
		}
		mv.addObject("businesses", optionService.getRepository().findByGroup(businessGroup));
		mv.addObject("regions", optionService.getRepository().findByGroup(regionGroup));
		mv.addObject("buyers", optionService.getRepository().findByGroup(buyerGroup));
		mv.addObject("assets", optionService.getRepository().findByGroup(asset));
		mv.addObject("continuelifes", optionService.getRepository().findByGroup(continuelife));
		mv.addObject("credits", optionService.getRepository().findByGroup(credit));
		mv.addObject("periods", optionService.getRepository().findByGroup(period));
		mv.addObject("customers", customerService.getRepository().findAll());
		return mv;
	}
	/**
	 *	获取开票信息List中的数据
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "selectCustomer", method = RequestMethod.POST)
	public Map<String, Object> saveCustomer1(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String CustomerId = request.getParameter("CustomerId");
		String key = request.getParameter("key");
		key=key==null?"":key;
		//String superior = "销售处";
		List<CustomerPayInfo> fucustoner = null;
        fucustoner = exdeCustomerPayInfoService.getMyPage(start, length, CustomerId,key);
		long count =0;		
		count=exdeCustomerPayInfoService.getMyPageCount(start, length, CustomerId,key);
		//System.out.println(count);
		map.put("data", fucustoner);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 *	获取开票信息List中的数据
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "getPayInfoList", method = RequestMethod.POST)
	public Map<String, Object> getPayInfoList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String CustomerId = request.getParameter("CustomerId");
		String key = request.getParameter("key");
		key=key==null?"":key;
		//String superior = "销售处";
		List<CustomerPayInfo> fucustoner = null;
		fucustoner = exdeCustomerPayInfoService.getMyPage(start, length, CustomerId,key);
		long count =0;		
		count=exdeCustomerPayInfoService.getMyPageCount(start, length, CustomerId,key);
		//System.out.println(count);
		map.put("data", fucustoner);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 *	获取邮寄信息List中的数据
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "getMailingInfoList", method = RequestMethod.POST)
	public Map<String, Object> getMailingInfoList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String CustomerId = request.getParameter("CustomerId");
		String key = request.getParameter("key");
		key=key==null?"":key;
		//String superior = "销售处";
		List<CustomerMailingInfo> fucustoner = null;
		fucustoner = customerMailingInfoService.getMyPage(start, length, CustomerId,key);
		long count =0;		
		count=customerMailingInfoService.getMyPageCount(start, length, CustomerId,key);
		//System.out.println(count);
		map.put("data", fucustoner);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 *	获取发货信息List中的数据
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "getSendInfoList", method = RequestMethod.POST)
	public Map<String, Object> getSendInfoList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String CustomerId = request.getParameter("CustomerId");
		String key = request.getParameter("key");
		key=key==null?"":key;
		//String superior = "销售处";
		List<CustomerSendInfo> fucustoner = null;
		fucustoner = customerSendInfoService.getMyPage(start, length, CustomerId,key);
		long count =0;		
		count=customerSendInfoService.getMyPageCount(start, length, CustomerId,key);
		//System.out.println(count);
		map.put("data", fucustoner);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	//// 保存客户
	@RequestMapping(value = "saveCustomer", method = RequestMethod.POST)
	public Map<String, Object> saveCustomer(HttpServletRequest request, @RequestBody Customer customer) {
			Map<String, Object> map = new HashMap<String, Object>();
			Account a = this.getMyAccount();
			User user = a.getUser();
			customer.setUser(user);
			Customer old=customerService.getRepository().findOne(customer.getId());
			if(old!=null){
				BeanUtils.copyProperties(customer, old, "createTime");
				customerService.getRepository().save(old);
				String content  = "编辑客户【" + customer.getCustomerName() + "】";
				operateLogService.log(user, "编辑客户", content);
			}else{
				customerService.getRepository().save(customer);
				String content  = "新增客户【" + customer.getCustomerName() + "】";
				operateLogService.log(user, "新增客户", content);
		}
		//获取开票信息中的字段
//		String CustomerId = customer.getId();
//		String identification = customer.getIdentification();
//		String invoicePhone = customer.getInvoicePhone();
//		String zipCode = customer.getZipCode();
//		String invoiceAddress = customer.getInvoiceAddress();
//		String invoiceBank = customer.getInvoiceBank();
//		String bankAccount = customer.getBankAccount();
//		String taxNumber = customer.getTaxNumber();
//		String invoiceMemo = customer.getInvoiceMemo();
//		String postUnit = customer.getPostUnit();
//		String postDelegate = customer.getPostDelegate();
//		String postPhone = customer.getPostPhone();
//		String postAddress = customer.getPostAddress();
//		String postZip = customer.getPostZip();
//		String business = customer.getBusiness();
//		String superior = customer.getSuperior();
//		String address = customer.getAddress();
//		String customerName = customer.getCustomerName();
//		String customerCode = customer.getCustomerCode();
		//SaleArea saleArea = customer.getSaleArea();
//		String id = request.getParameter("customerId");
//		if(id == ""){
//			if(invoiceAddress != ""){
//				exdeCustomerPayInfoService.saveCustomer(CustomerId, identification, invoicePhone, zipCode,
//						invoiceAddress, invoiceBank, bankAccount, taxNumber, invoiceMemo,postUnit,postDelegate,postPhone,postAddress,postZip,
//						business,superior,address,customerName,customerCode);
//			}
//		}
		//customerSaveSonService.getCustomerPayInfoRepository().save();
			
			
		map.put("code", 0);
		String customerId = customer.getId();
		Date createTime = customer.getCreateTime();
		map.put("customerId", customerId);
		map.put("createTime", createTime);
		return map;
	}
////审核
	@RequestMapping(value = "shCustomer", method = RequestMethod.POST)
	public Map<String, Object> shCustomer(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			String id = request.getParameter("id");
			System.out.println(id);
			Account a = this.getMyAccount();
			String name = a.getUser().getName();
			long count = exdeCustomerAllocationService.getAllUserCount(name);
			if(count > 0){
				if(id != null){
					Customer old=customerService.getRepository().findOne(id);
					if(old != null){
						old.setAuditState("已审核");
					}
					customerService.getRepository().save(old);
				}
				map.put("sata", 1);
			}else{
				map.put("sata", 2);
			}
			map.put("code", 0);
			return map;
	}
	/**
	 * 客户信息界面开票信息dialog中的保存按钮
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "saveCustomerPayInfo", method = RequestMethod.POST)
	public Map<String, Object> saveCustomerPayInfo(HttpServletRequest request, @RequestBody CustomerPayInfo customerPayInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		int isDefaultHost=customerPayInfo.getIsDefaultHost();
		int isDefaultPart=customerPayInfo.getIsDefaultPart();
		
		if(isDefaultHost==1){
			CustomerPayInfo oldDefault =exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findByCustomer_IdAndIsDefaultHost(customerPayInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerPayInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultHost(0);
				exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save(oldDefault);
			}
			
		}
		if(isDefaultPart==1){
			CustomerPayInfo oldDefault =exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findByCustomer_IdAndIsDefaultPart(customerPayInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerPayInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultPart(0);
				exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save(oldDefault);
			}
			
		}
		
		CustomerPayInfo old=exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findOne(customerPayInfo.getId());
		if(null==old) {
			
			String uuid = java.util.UUID.randomUUID().toString();
			customerPayInfo.setId(uuid);
			exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save(customerPayInfo);
			
		}else{
			
			BeanUtils.copyProperties(customerPayInfo, old, "createTime");
			
			exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save(old);
			
			
			
		}
		map.put("code", 0);
		map.put("customerId", customerPayInfo.getCustomer().getId());
		return map;
	}
	/**
	 * 客户信息界面开票信息dialog中的删除按钮
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteCustomerPayInfo", method = RequestMethod.GET)
	public Map<String, Object> deleteCustomerPayInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		//customerIdexdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save();
		exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().delete(id);
		map.put("code", 0);
		//map.put("customerId", customerPayInfo.getCustomerId());
		return map;
	}
	
	
	/**
	 * 客户信息界面邮寄信息dialog中的保存按钮
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "saveCustomerMailingInfo", method = RequestMethod.POST)
	public Map<String, Object> saveCustomerMailinInfo(HttpServletRequest request, @RequestBody CustomerMailingInfo customerMailingInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		
		int isDefaultHost=customerMailingInfo.getIsDefaultHost();
		int isDefaultPart=customerMailingInfo.getIsDefaultPart();
		
		if(isDefaultHost==1){
			CustomerMailingInfo oldDefault =customerMailingInfoService.getCustomerMailingInfoRepository().findByCustomer_IdAndIsDefaultHost(customerMailingInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerMailingInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultHost(0);
				customerMailingInfoService.getCustomerMailingInfoRepository().save(oldDefault);
			}
			
		}
		if(isDefaultPart==1){
			CustomerMailingInfo oldDefault =customerMailingInfoService.getCustomerMailingInfoRepository().findByCustomer_IdAndIsDefaultPart(customerMailingInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerMailingInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultPart(0);
				customerMailingInfoService.getCustomerMailingInfoRepository().save(oldDefault);
			}
			
		}
		
		CustomerMailingInfo old=customerMailingInfoService.getCustomerMailingInfoRepository().findOne(customerMailingInfo.getId());
		if(null==old) {
			String uuid = java.util.UUID.randomUUID().toString();
			customerMailingInfo.setId(uuid);
			customerMailingInfoService.getCustomerMailingInfoRepository().save(customerMailingInfo);
		}else{
			BeanUtils.copyProperties(customerMailingInfo, old, "createTime");
			customerMailingInfoService.getCustomerMailingInfoRepository().save(old);
		}
		map.put("code", 0);
		map.put("customerId", customerMailingInfo.getCustomer().getId());
		return map;
	}
	/**
	 * 客户信息界面邮寄信息dialog中的删除按钮
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteCustomerMailingInfo", method = RequestMethod.GET)
	public Map<String, Object> deleteCustomerMailinInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		//customerIdexdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save();
		customerMailingInfoService.getCustomerMailingInfoRepository().delete(id);
		map.put("code", 0);
		//map.put("customerId", customerPayInfo.getCustomerId());
		return map;
	}
	
	
	/**
	 * 客户信息界面邮寄信息dialog中的保存按钮
	 * @param request
	 * @param customer
	 * @return
	 */
	@RequestMapping(value = "saveCustomerSendInfo", method = RequestMethod.POST)
	public Map<String, Object> saveCustomerSendInfo(HttpServletRequest request, @RequestBody CustomerSendInfo customerSendInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		int isDefaultHost=customerSendInfo.getIsDefaultHost();
		int isDefaultPart=customerSendInfo.getIsDefaultPart();
		
		if(isDefaultHost==1){
			CustomerSendInfo oldDefault =customerSendInfoService.getCustomerSendInfoRepository().findByCustomer_IdAndIsDefaultHost(customerSendInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerSendInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultHost(0);
				customerSendInfoService.getCustomerSendInfoRepository().save(oldDefault);
			}
			
		}
		if(isDefaultPart==1){
			CustomerSendInfo oldDefault =customerSendInfoService.getCustomerSendInfoRepository().findByCustomer_IdAndIsDefaultPart(customerSendInfo.getCustomer().getId(),1);
			if(null!=oldDefault&&!customerSendInfo.getId().equals(oldDefault.getId())){
				oldDefault.setIsDefaultPart(0);
				customerSendInfoService.getCustomerSendInfoRepository().save(oldDefault);
			}
			
		}
		
		
		
		CustomerSendInfo old=customerSendInfoService.getCustomerSendInfoRepository().findOne(customerSendInfo.getId());
		if(null==old) {
			String uuid = java.util.UUID.randomUUID().toString();
			customerSendInfo.setId(uuid);
			customerSendInfoService.getCustomerSendInfoRepository().save(customerSendInfo);
		}else{
			BeanUtils.copyProperties(customerSendInfo, old, "createTime");
			customerSendInfoService.getCustomerSendInfoRepository().save(old);
		}
		map.put("code", 0);
		map.put("customerId", customerSendInfo.getCustomer().getId());
		return map;
	}
	/**
	 * 客户信息界面邮寄信息dialog中的删除按钮
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteCustomerSendInfo", method = RequestMethod.GET)
	public Map<String, Object> deleteCustomerSendInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		//customerIdexdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().save();
		customerSendInfoService.getCustomerSendInfoRepository().delete(id);
		map.put("code", 0);
		//map.put("customerId", customerPayInfo.getCustomerId());
		return map;
	}
	
	
	
	
	
	
	
	
	/// 删除客户
	@RequestMapping(value = "delcustomer", method = RequestMethod.GET)
	public Map<String, Object> delCustomer(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Customer> customers = new ArrayList<Customer>();
		for (int i = 0; i < id.length; i++) {
			String customerId = id[i];
			Customer customer = new Customer();
			customer.setId(customerId);
			customers.add(customer);
			List<KeyContact> ks = customerService.getKeyContactRepository().findKeyContacts(customerId);
			customerService.getKeyContactRepository().deleteInBatch(ks);
			List<CustomerVisiting> vs = customerVisitingService.getCustomerVisitingRepository()
					.getVisitsById(customerId);
			for (CustomerVisiting v : vs) {
				String visitId = v.getId();
				customerVisitingService.getCustomerVisitingCostRepository().deleteCost(visitId);
				customerVisitingService.getCustomerVisitPersonRepository().deletePerson(visitId);
				customerVisitingService.getCustomerVisitingRepository().delete(visitId);
			}
			
			List<CustomerSendInfo>sends=customerSendInfoService.getCustomerSendInfoRepository().findByCustomer_Id(customerId);
			if(!sends.isEmpty())customerSendInfoService.getCustomerSendInfoRepository().delete(sends);
			
			List<CustomerPayInfo>pays=exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findByCustomer_Id(customerId);
			if(!sends.isEmpty())exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().delete(pays);
			
			List<CustomerMailingInfo>mailings=customerMailingInfoService.getCustomerMailingInfoRepository().findByCustomer_Id(customerId);
			if(!sends.isEmpty())customerMailingInfoService.getCustomerMailingInfoRepository().delete(mailings);
			
		}
			Account a = this.getMyAccount();
			User user = a.getUser();
			for(Customer c:customers){
				Customer old=customerService.getRepository().findOne(c.getId());
				String content  = "删除客户【" + old.getCustomerName() + "】";
				operateLogService.log(user, "删除客户", content);
			}
		customerService.getRepository().deleteInBatch(customers);
		map.put("code", 0);
		return map;
	}

	
	
	
	
	
	
	
	// 获得客户信息通过ID
	@RequestMapping(value = "getCustomer", method = RequestMethod.GET)
	public Map<String, Object> getCustomer(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId = request.getParameter("customerId");
		Customer c = customerService.getRepository().findById(customerId);
		map.put("customer", c);
		return map;
	}

	///// 保存客户相关的关键联系人
	@RequestMapping(value = "saveKeyContact", method = RequestMethod.POST)
	public Map<String, Object> saveKeyContact(HttpServletRequest request, @RequestBody KeyContact keyContact) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = keyContact.getCustomer().getId();
		Customer c = customerService.getRepository().findById(id);
		keyContact.setCustomer(c);
		customerService.getKeyContactRepository().save(keyContact);
		map.put("code", 0);
		return map;
	}

	/*
	 * 删除客户的关键联系人
	 * 
	 */
	@RequestMapping(value = "delKey", method = RequestMethod.GET)
	public Map<String, Object> delKeyContact(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<KeyContact> keys = new ArrayList<KeyContact>();
		for (int i = 0; i < id.length; i++) {
			String keyId = id[i];
			KeyContact k = new KeyContact();
			k.setId(keyId);
			keys.add(k);
		}
		customerService.getKeyContactRepository().deleteInBatch(keys);
		map.put("code", 0);
		return map;
	}

	/*
	 * 获得客户相关的销售信息
	 */
	@RequestMapping(value = "getchance", method = RequestMethod.GET)
	public Map<String, Object> getChance(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId = request.getParameter("customerId");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<KeyContact> keyContacts = new ArrayList<KeyContact>();
		if (StringUtils.hasText(customerId)) {
			keyContacts = customerService.getKeyContacts(start, length, key, customerId);
		}
		long count = 0;
		if (key != null) {
			count = customerService.getKeyContactRepository().getKeyCount(customerId, key);
		} else {
			count = customerService.getKeyContactRepository().getKeyCount(customerId);
		}
		map.put("data", keyContacts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/*
	 * 获得客户相关的销售信息
	 */
	@RequestMapping(value = "updataSareaName", method = RequestMethod.GET)
	public Map<String, Object> updataSareaName(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String a = customerService.updataSareaName();
		map.put("data", a);
		return map;
	}
	/*
	 * 获得客户相关的销售信息
	 */
	@RequestMapping(value = "getDefaultInfo", method = RequestMethod.GET)
	public Map<String, Object> getDefaultInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String customerId=request.getParameter("customerId");
		String hostType=request.getParameter("hostType");
		CustomerPayInfo  customerPayInfo; 
	    CustomerMailingInfo customerMailingInfo;
		if(hostType.equals("1")){
			customerPayInfo=exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findByCustomer_IdAndIsDefaultHost(customerId, 1);
		    customerMailingInfo=customerMailingInfoService.getCustomerMailingInfoRepository().findByCustomer_IdAndIsDefaultHost(customerId, 1);
		}else{
			customerPayInfo=exdeCustomerPayInfoService.getEXDECustomerPayInfoRepository().findByCustomer_IdAndIsDefaultPart(customerId, 1);
		    customerMailingInfo=customerMailingInfoService.getCustomerMailingInfoRepository().findByCustomer_IdAndIsDefaultPart(customerId, 1);
		}
		List<Object> needData=new ArrayList<Object>();
		needData.add(customerPayInfo);
		needData.add(customerMailingInfo);
		map.put("data", needData);
		return map;
	}
}
